#!/bin/sh

# This file is part of libmarco
# http://code.google.com/p/libmarco/

# Script to tweet from the command-line.
# 0. Requires curl
# 1. Set the parameters below
# 2. Invoke with arguments to append to the current entry
#      twitter-journal.sh "Bla bla"
#      twitter-journal.sh "More Bla bla"
# 3. Invoke withouth arguments to post the current entry
#    (In this example: "Bla bla, More Bla bla")
# If the message exceedes 140 character the editor is invoked

# Twitter parameters
user="USERNAME"
pass="PASSWORD"

# Various parameters
journal_file="$HOME/.twitter-journal.temp"
editor_command="vim"

function journal_current_size () {
    ccount=`cat $journal_file | wc -c | awk '{print $1}'`;
}


function journal_print () {
    echo " *** Today's log ($ccount characters) *** "
    cat $journal_file | fold -s  -w 40
    echo
    echo "--"
    echo
}

function journal_manual_edit () {
    echo "Warning: Message too long ($ccount characters)"
    echo "Press enter to edit manually"
    read
    $editor_command $journal_file
}


function journal_commit () {
    echo "Committing today's log..."
    
    journal_current_size
    if [[ $ccount == 0 ]]; then
        echo "Message is empty! (check $journal_file)"
        exit 1
    elif [[ $ccount -gt 140 ]]; then
        journal_manual_edit
        exit 1
    fi

    journal_print
    echo "Press enter to commit"
    read

    curl --basic --user "$user:$pass" --data-ascii \
        "status=`cat $journal_file | tr ' ' '+'`" \
        "http://twitter.com/statuses/update.json" >& /dev/null

    if [[ $? != 0 ]]; then
        echo "Post failed"
        exit 1
    fi
    echo "Post successful, clearing journal"
    rm -f $journal_file
}

function journal_append () {
    echo "Appending to today's log..."
    if [[ ! -e $journal_file ]]; then
        touch $journal_file
        echo -n "$@" > $journal_file
    else
        echo -n ", $@" >> $journal_file
    fi
    
    journal_current_size
    journal_print
    
    if [[ $ccount -gt 140 ]]; then
        journal_manual_edit
    fi
    
}


curl --version >/dev/null || ( echo "curl not found" && exit 1 )

if [[ $@ == "" ]]; then
    journal_commit
else
    journal_append $@
fi
exit 0
